﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MALRECrewrite.ViewModels;
using System.Threading;
using MALRECrewrite.Etc;
using System.Windows.Media.Animation;
using System.Diagnostics;
using MALRECrewrite.Models;
using System.Threading.Tasks;
using System.Windows.Threading;
using Microsoft.Expression.Interactivity.Core;
using MALRECrewrite.View;

namespace MALRECrewrite
{
    public partial class MainWindow : Window
    {
        private bool _IsTreeView = false;

        public MainWindow()
        {
            InitializeComponent();

            this.DataContext = App.DataModel;
            this.Loaded += delegate
            {
                Task t = App.DataModel.Load();

                t.ContinueWith(delegate
                {
                    if (MALRECrewrite.Properties.Settings.Default.IsTreeView)
                    {
                        Dispatcher.BeginInvoke((Action)delegate
                        {
                            TreeViewOrListButton_Click(null, null);
                        });
                    }
                });
            };

            this.Closing += (s, e) =>
            {
                e.Cancel = true;
                this.Hide();
                new Thread(() =>
                {
                    App.DataModel.Save();
                    Dispatcher.InvokeShutdown();
                }).Start();
            };
        }

        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listBox.SelectedItem == null)
                return;

            App.DataModel.GetLanguagesFromAniSearch(App.DataModel.SelectedRecommendation);

            if(!App.DataModel.ShowAllInfos)
                App.DataModel.SortedRecommendations.Where(x=> x.ShowAllInfo).ToList().ForEach(y=>y.ShowAllInfo = false);

            (listBox.SelectedItem as SortedRecommendation).ShowAllInfo = true;

            if (col3.Width == new GridLength(4, GridUnitType.Star))
            {
                if (App.DataModel.SelectedRecommendation != null)
                    webBrowser.Source = new Uri(App.DataModel.SelectedRecommendation.Uri);
            }
        }

        private void ListBoxItem_DoubleClick(object sender, MouseEventArgs e)
        {
            RightColumSlider.IsChecked = true;
        }

        private void RightColumSlider_Checked(object sender, RoutedEventArgs e)
        {
            double val = col1.Width.Value + col2.Width.Value;

            col3.Width = new GridLength(9.0 / (this.ActualWidth / val), GridUnitType.Star);

            GridLengthAnimation gridLengthAnim = new GridLengthAnimation();
            gridLengthAnim.From = col3.Width;
            gridLengthAnim.To = new GridLength(4, GridUnitType.Star);
            gridLengthAnim.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 300));

            Storyboard.SetTargetName(gridLengthAnim, col3.Name);
            Storyboard.SetTargetProperty(gridLengthAnim, new PropertyPath("Width"));

            Storyboard board = new Storyboard();
            board.Children.Add(gridLengthAnim);

            board.Completed += delegate
                {
                    listBox.ScrollIntoView(listBox.SelectedItem);
                };

            board.Begin(this);

            if (App.DataModel.SelectedRecommendation != null)
                webBrowser.Source = new Uri(App.DataModel.SelectedRecommendation.Uri);
        }

        private void RightColumSlider_Unchecked(object sender, RoutedEventArgs e)
        {
            double val = col1.Width.Value + col2.Width.Value + col3.Width.Value;
            col3.Width = new GridLength((this.ActualWidth / val) * 4, GridUnitType.Pixel);

            GridLengthAnimation gridLengthAnim = new GridLengthAnimation();
            gridLengthAnim.From = col3.Width;
            gridLengthAnim.To = new GridLength(9, GridUnitType.Pixel);
            gridLengthAnim.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 300));

            Storyboard.SetTargetName(gridLengthAnim, col3.Name);
            Storyboard.SetTargetProperty(gridLengthAnim, new PropertyPath("Width"));

            Storyboard board = new Storyboard();
            board.Children.Add(gridLengthAnim);

            board.Begin(this);
        }

        private void LoadAnimesButton_Click(object sender, RoutedEventArgs e)
        {
            if(MessageBox.Show("Sure?","",MessageBoxButton.YesNo,MessageBoxImage.Warning) == MessageBoxResult.Yes)
                App.DataModel.LoadAnimeList();
        }

        private void ApplyGenreButton_Click(object sender, RoutedEventArgs e)
        {
            App.DataModel.SortRecommendationsByGenre();
        }

        private void SelectAllButton_Click(object sender, RoutedEventArgs e)
        {
            App.DataModel.Genres.ForEach(x => x.IsEnabled = true);
        }

        private void SelectNoneButton_Click(object sender, RoutedEventArgs e)
        {
            App.DataModel.Genres.ForEach(x => x.IsEnabled = false);
        }

        private void LeftColumSlider_Checked(object sender, RoutedEventArgs e)
        {
            double val = col3.Width.Value + col2.Width.Value;

            col1.Width = new GridLength(9.0 / (this.ActualWidth / val), GridUnitType.Star);

            GridLengthAnimation gridLengthAnim = new GridLengthAnimation();
            gridLengthAnim.From = col1.Width;
            gridLengthAnim.To = new GridLength(1, GridUnitType.Star);
            gridLengthAnim.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 300));

            Storyboard.SetTargetName(gridLengthAnim, col1.Name);
            Storyboard.SetTargetProperty(gridLengthAnim, new PropertyPath("Width"));

            Storyboard board = new Storyboard();
            board.Children.Add(gridLengthAnim);
            board.Begin(this);
        }

        private void LeftColumSlider_Unchecked(object sender, RoutedEventArgs e)
        {
            double val = col1.Width.Value + col2.Width.Value + col3.Width.Value;
            col1.Width = new GridLength((this.ActualWidth / val) * 1, GridUnitType.Pixel);

            GridLengthAnimation gridLengthAnim = new GridLengthAnimation();
            gridLengthAnim.From = col1.Width;
            gridLengthAnim.To = new GridLength(9, GridUnitType.Pixel);
            gridLengthAnim.Duration = new Duration(new TimeSpan(0, 0, 0, 0, 300));

            Storyboard.SetTargetName(gridLengthAnim, col1.Name);
            Storyboard.SetTargetProperty(gridLengthAnim, new PropertyPath("Width"));

            Storyboard board = new Storyboard();
            board.Children.Add(gridLengthAnim);

            board.Begin(this);
        }

        private void ToggleVisualStylesButton_Click(object sender, RoutedEventArgs e)
        {
            App.DataModel.ShowAllInfos = !App.DataModel.ShowAllInfos;
        }

        private void webBrowser_BeginNavigation(object sender, Awesomium.Core.BeginNavigationEventArgs e)
        {
            Storyboard sb = (Storyboard)this.FindResource("WebbrowserSiteChangedAnimationStart");
            sb.Begin();
        }

        private void webBrowser_DomReady(object sender, EventArgs e)
        {
            Storyboard sb = (Storyboard)this.FindResource("WebbrowserSiteChangedAnimationEnd");
            sb.Begin();
        }

        private void SelectAllAnimesButton_Click(object sender, RoutedEventArgs e)
        {
            if (_IsTreeView)
                App.DataModel.AnimeGroups.ToList().ForEach(x => x.IsChecked = true);
            else
                App.DataModel.Animes.ForEach(x => x.IsActive = true);
        }

        private void SelectNoneAnimesButton_Click(object sender, RoutedEventArgs e)
        {
            if (_IsTreeView)
                App.DataModel.AnimeGroups.ToList().ForEach(x => x.IsChecked = false);
            else
                App.DataModel.Animes.ForEach(x => x.IsActive = false);
        }

        private void ApplyAnimesButton_Click(object sender, RoutedEventArgs e)
        {
            App.DataModel.SortAnimeRecommendations();
        }

        private void UpdateAnimesButton_Click(object sender, RoutedEventArgs e)
        {
            App.DataModel.UpdateAnimeList();
        }

        private void MenuItem_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            App.DataModel.AddToBlacklist();
        }

        private void RemoveFromBlacklistButton_Click(object sender, RoutedEventArgs e)
        {
            if (BlacklistListbox.SelectedItem != null)
                App.DataModel.RemoveFromBlacklist(BlacklistListbox.SelectedItem as Recommendation);
        }

        DispatcherTimer dt = new DispatcherTimer();
        private void TextBlock_TargetUpdated(object sender, DataTransferEventArgs e)
        {
            if (App.DataModel == null || App.DataModel.Message == null || App.DataModel.Message == "")
                return;

            grid2.Visibility = System.Windows.Visibility.Visible;

            if (dt.IsEnabled)
            {
                dt.Stop();
                dt.Interval = TimeSpan.FromSeconds(0);
                dt.Interval = TimeSpan.FromSeconds(5);
            }

            dt.Tick += delegate
            {
                grid2.Visibility = System.Windows.Visibility.Hidden;
            };
            dt.Interval = TimeSpan.FromSeconds(5);
            dt.Start();

        }

        private void squelsButton_Click(object sender, RoutedEventArgs e)
        {
            new Sequels().Show();
        }

        private void Download10Languages_Click(object sender, RoutedEventArgs e)
        {
            App.DataModel.GetNext10Langauges();
        }

        private void TreeViewOrListButton_Click(object sender, RoutedEventArgs e)
        {
            if (!_IsTreeView)
            {
                App.DataModel.GenerateAnimeGroups();
                AnimeTreeview.Visibility = System.Windows.Visibility.Visible;

                _IsTreeView = true;
            }
            else
            {
                AnimeTreeview.Visibility = System.Windows.Visibility.Collapsed;
                _IsTreeView = false;
            }

            MALRECrewrite.Properties.Settings.Default.IsTreeView = _IsTreeView;
            MALRECrewrite.Properties.Settings.Default.Save();
        }
    }
}
